package com.woniuxy.shiro;

import com.woniuxy.service.ManagerLoginService;
import com.woniuxy.utils.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired(required = false)
    ManagerLoginService managerLoginService;

    //做授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String token = principals.getPrimaryPrincipal()+"";
        String username = JWTUtil.getUsername(token);
        //去数据库查询该用户所有的角色和权限
        Set<String> roles = managerLoginService.findAllRoles(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        //获取权限
        Set<String> perms = managerLoginService.findAllPerms(username);
        simpleAuthorizationInfo.setStringPermissions(perms);
        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MyJsonWebToken myJsonWebToken =(MyJsonWebToken) authenticationToken;
        //这里是我们前端传来的token
        String token = myJsonWebToken.getCredentials()+"";
        String username = JWTUtil.getUsername(token);

        //使用username去数据库查询密码
        String password = managerLoginService.findPassword(username);
        //校验token是否正常 password 是用来做盐的 加密更加散列
        boolean verify = JWTUtil.verify(token,username,password);
        if(verify){
            //直接把token封装进去
            return new SimpleAuthenticationInfo(token,token,"myRealm");
        }else {
            throw new AuthenticationException("token被篡改，请重新登录");
        }
    }
}
